package com.luoxiang.socialandroid.utils

import android.util.Log
import com.blankj.utilcode.util.LogUtils
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.jeremyliao.liveeventbus.LiveEventBus
import com.luoxiang.lib_common.bean.ResponseDTO
import com.luoxiang.lib_common.common.Constants.MmkvConst.KEY
import com.luoxiang.socialandroid.bean.NumberBean
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody


class ResponseDecryptLogInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        var response = chain.proceed(request)
        if (response.isSuccessful) {
            val responseBody = response.body
            if (responseBody != null) {
                /*开始解密*/
                val source = responseBody.source()
                source.request(java.lang.Long.MAX_VALUE)
                val buffer = source.buffer
                val charset = Charsets.UTF_8
                val contentType = responseBody.contentType()
                contentType?.charset(charset)
                val bodyString = buffer.clone().readString(charset)
                try {
                    val numberBean = Gson().fromJson<NumberBean>(bodyString,object : TypeToken<NumberBean>() {}.type)
                    val decryptData = AESUtil.aesDecryptString(numberBean.data, KEY)
                    Log.d("decryptData",decryptData)
                   val responseDTO: ResponseDTO = Gson().fromJson(decryptData,object : TypeToken<ResponseDTO>(){}.type)
                    if (responseDTO.code==2){
                        LogUtils.i("tokenfale", "发送了$responseDTO  http:${response.request.url}")
                        LiveEventBus.get<Any>("tokenFailure").post(null)
                    }
                    val newResponseBody = bodyString.toResponseBody(contentType)
                    response = response.newBuilder().body(newResponseBody).build()
                } catch (e: Exception) {
                    val newResponseBody = bodyString.toResponseBody(contentType)
                    response = response.newBuilder().body(newResponseBody).build()
                }
            }
        }
        return response
    }
}